<template>
  <h3>路由导航守卫 演示 (包括钩子的注销, 打开日志查看输出)</h3>

  <p>
    <router-link class="link" to="/navguard/home">主页</router-link>
    <router-link class="link" to="/navguard/msg">消息列表</router-link>
  </p>
  <router-view></router-view>

  <hr>
  <p>
    <b>完整的导航解析流程</b><br>
    1. 导航被触发。<br>
    2. 在失活的组件里调用 beforeRouteLeave 守卫。<br>
    3. 调用全局的 beforeEach 守卫。<br>
    4. 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。<br>
    5. 在路由配置里调用 beforeEnter。<br>
    6. 解析异步路由组件。<br>
    7. 在被激活的组件里调用 beforeRouteEnter。<br>
    8. 调用全局的 beforeResolve 守卫(2.5+)。<br>
    9. 导航被确认。<br>
    10.调用全局的 afterEach 钩子。<br>
    11.触发 DOM 更新。<br>
    12.调用 beforeRouteEnter 守卫中传给 next 的回调函数，创建好的组件实例会作为回调函数的参数传入。<br><br>
    
    官方文档: <a href="https://router.vuejs.org/zh/guide/advanced/navigation-guards.html"><b>导航守卫</b></a>&nbsp;,&nbsp;
    <a href="https://router.vuejs.org/zh/guide/advanced/navigation-failures.html"><b>navigation failures</b></a>&nbsp;,&nbsp;
    <a href="https://router.vuejs.org/zh/guide/advanced/composition-api.html#%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB"><b>组合式API中的导航守卫</b></a>
  </p>
</template>

<script>
import {useRouter} from 'vue-router'
import { onBeforeUnmount } from 'vue'

export default {
  setup() {
    let router = useRouter()
    
    //全局前置守卫 (有可选的第三个参数 next)
    let beforeEachGuard = (to, from) => {
      console.log('*** beforeEach 全局前置守卫', 'to:', to.path, 'from:', from.path)
      return true //返回false: 取消当前的导航。其他情况(包括不return true)则正常跳转.
    }
    let delBeforeEach = router.beforeEach(beforeEachGuard)

    //全局解析守卫
    let beforeResolveGuard = (to) => {
      console.log('*** beforeResolve 全局解析守卫', 'to:', to.path)
    }
    let delBeforeResolve = router.beforeResolve(beforeResolveGuard)

    //全局后置钩子 (可带第三个参数 navigation failures)
    let afterEachGuard = (to, from) => {
      console.log('*** afterEach 全局后置钩子', 'to:', to.path, 'from:', from.path)
    }
    let delAfterEach = router.afterEach(afterEachGuard)

    onBeforeUnmount(()=>{
      //注销各个已经注册的全局守卫钩子
      delBeforeEach(beforeEachGuard)
      delBeforeResolve(beforeResolveGuard)
      delAfterEach(afterEachGuard)
    })
  },
}
</script>

<style scoped>
  .link {
    display: inline-block;
    width: 88px;
    height: 36px;
    line-height: 36px;
    /* padding: 5px 15px; works except border and bold font */

    margin-top: 5px;
    margin-left: 10px;
    text-align: center;
  }

  .router-link-active {
    font-weight: bold;
    color: orange;
    background-color: #205081;
    border-radius: 2px;
    /* 应用于初始状态，因此此转换将应用于返回状态 */
    transition: background 0.25s ease-in;
  }

  .router-link-active:hover {
    background-color: #3b73af;
    /* 应用于悬停状态，因此在触发悬停时将应用此过渡 */
    transition: background 0.35s ease-out;
  }

  .router-link-exact-active {
    color: whitesmoke;
  }

  .link:hover {
    border-radius: 3px;
    /* border: 1px solid burlywood; */
    background-color: #3b73af;
    color: white;
  }
</style>